package com.mqtt.demo.mqtt;

import cn.hutool.core.util.ObjectUtil;
import com.mqtt.demo.callback.MessageCallback;
import com.mqtt.demo.constant.Constant;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @ClassName MyMqttClient
 * @Description mqtt客户端
 * @Author zhengmw
 * @Data 2024/7/25 18:18
 */
@Slf4j
@Component
public class MyMqttClient {


    @Value("${mqtt.qos}")
    private int qos;

    private MqttClient client;

    @Resource
    private MqttManager mqttManager;


    /**
     * @Description
     * 
     * @Param topic 
     * @Return void
     * @Author zhengmw
     * @Date 2024/7/25 19:20     
     */
    public void subscribe(String topic, MqttCallback mqttCallback) throws MqttException {
        log.info("**********连接并订阅消息");
        if (ObjectUtil.isNull(client)) {
            client = mqttManager.connect();
        }
        // 设置回调
        client.setCallback(mqttCallback);
        // 订阅消息
        client.subscribe(topic, qos);

        log.info("开始监听mqtt队列 {}", Constant.SUBSCRIBE_TOPIC);
    }



    /**
     * @Description 连接并订阅消息
     *
     * @Return void
     * @Author zhengmw
     * @Date 2024/7/25 19:42
     */
    public void connectAndSubscribe() throws MqttException{

        subscribe(Constant.SUBSCRIBE_TOPIC, new MessageCallback());
    }

    /**
     * @Description
     * 
     * @Param topic
     * @Param message 
     * @Return void
     * @Author zhengmw
     * @Date 2024/7/25 19:56     
     */
    public void publish(String topic, String message) throws MqttException{
        if (ObjectUtil.isNull(client)) {
            client = mqttManager.connect();
        }
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        mqttMessage.setQos(qos);
        // 消息发布
        client.publish(topic, mqttMessage);
        log.info("************* 消息发布成功");
    }
        
}
